package com.zhugang.week13.hash;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @program algorithms
 * @description: findRepeatNumber
 * @author: chanzhugang
 * @create: 2022/12/06 15:28
 */
public class FindRepeatNumber {

    /**
     * 剑指offer03 数组中重复的数字
     * https://leetcode.cn/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
     *
     * @param nums
     * @return
     */
    public int findRepeatNumber(int[] nums) {
        /**
         * 哈希集合直接搞
         */
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            if (set.contains(num)) {
                return num;
            }
            set.add(num);
        }
        return -1;
    }

    public int findRepeatNumber2(int[] nums) {
        /**
         * 排序，比较相邻元素是否相等
         */
        Arrays.sort(nums);

        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                return nums[i];
            }
        }
        return -1;
    }
}